//
//  TokenBlacklist.swift
//  hello
//
//  Created by yafei li on 2025/10/10.
//


import Vapor
import Redis
import Crypto

//Token 黑名单
struct TokenBlackList {
    private let tokenLifespan: TimeInterval = 60 * 60 * 24 * 7 // 7天
    private func redisKey(for tokenHash: String) -> RedisKey {
        return RedisKey(tokenHash)
    }
    func save(tokenHash: String, userId: UUID, on req: Request) async throws {
       let key = redisKey(for: tokenHash)
       try await req.redis.setex(key, toJSON: userId.uuidString, expirationInSeconds: Int(tokenLifespan))
    }
    
    /// 检查 Token 是否存在 于黑名单中
    func exists(tokenHash: String, on req: Request) async throws -> Bool {
        let key = redisKey(for: tokenHash)
        let result =  try await req.redis.exists([key])
        if result > 0 {
            return true
        }else{
            return false
        }
    }
}
